/**
 * Created by wangkui on 2015/12/23.
 * 获取微信签名，分享时候使用
 */

var _ = require('lodash'),
    async = require("async"),
    request = require('request'),
    url = require("url");
var config = require('./../config');
//更新为redis数据缓存方式{2015-12-23 created by wangkui}
var CachemanRedis = require('cacheman-redis');
var cache = new CachemanRedis(config.cachestore);

//生成签名的时间戳
var createTimestamp = function () {
    return parseInt(new Date().getTime() / 1000) + '';
};
//生成签名的随机串
var createNonceStr = function () {
    return Math.random().toString(36).substr(2, 15);
};
var raw = function (args) {
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    var string = '';
    for (var k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
};
//获取微信token
var _initToken = function(callback){
    var timestamp = createTimestamp();
    var _url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx26fe4ccc982d1e1b&secret=6d8ac447fd198ddeef5268d6c7976697";
    request.get({url: _url, json: true}, function (error, response, body){
        if (!error && response.statusCode === 200)
        {
            var access_token = body.access_token;
            var expires_in = body.expires_in;
            var token = {
                token:access_token,
                timestamp:timestamp,
                expires:expires_in
            };
            callback(token);
        }else{
            console.log(body);
            //出错则重启请求
            var delayTime = (parseInt(expires_in) - 100)*1000;
            setTimeout(_initToken,delayTime);
        }
    });
}
//获取微信ticket
var _ticket=function(type,token,callback){
    var key = "weixin_ticket_"+type;
    var newticket;
    //请求ticket
    var _ticketurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token.token+ "&type="+type;

    request.get({url: _ticketurl, json: true}, function (error, response, body){
        if (!error && response.statusCode === 200) {
            newticket = {ticket:body.ticket, timestamp:token.timestamp, expires:body.expires_in};
            callback(newticket);
        }else {
            console.log(body);
            //出错则重启请求
            var delayTime = (parseInt(body.expires_in) - 100)*1000;
            setTimeout(_ticket,delayTime);
        }
    });
};

//获取微信票据(jsApi)
var _getticketdata = function(type,cb){
    var token;
    var ticket;
    async.series({
        //获取微信token
        token:function(callback){
            _initToken(function(data){
                token=data;
                callback();
            });
        },
        //获取微信票据
        ticket:function(callback){
            _ticket(type,token,function(data){
                ticket=data;
                callback();
            })
        }
    },function(err,result){
        cb(ticket);
    });
}


//获取签名Signature
exports.getsignature = function(req,res){
    var arg=url.parse(req.url,true).query;
    var wxsign;
    var key = "weixin_signature_jsapi";
    cache.get(key,function(err,value){
        if(err||value==null||value==''){
            _getticketdata('jsapi',function(data)
            {
                var ret = {
                    jsapi_ticket: data.ticket,
                    nonceStr: createNonceStr(),
                    timestamp: createTimestamp(),
                    url: arg.url
                };
                var str = raw(ret);
                jsSHA = require('jssha');
                shaObj = new jsSHA(str, 'TEXT');
                ret.signature = shaObj.getHash('SHA-1', 'HEX');
                wxsign={
                    appId:'wx26fe4ccc982d1e1b',
                    timestamp:ret.timestamp,
                    nonceStr:ret.nonceStr,
                    signature:ret.signature,
                    url:arg.url
                };
                cache.set(key,wxsign,data.expires-200,function(err){
                    if(err){console.log(err);}
                });
                return res.json(wxsign);
            });
        }else{
            return res.json(value);
        }
    });
}